/**
 * 详情对话框
 */


var H_APPEAL = "0";
var H_ORDERED = "1";
var H_INPUT = "2";
var H_DONE = "3";

var H_APPEAL_DESC = "申请阶段";
var H_ORDERED_DESC = "下单阶段";
var H_INPUT_DESC = "入库阶段";
var H_DONE_DESC = "完成阶段";


layui.config({});
layui.use(['form', 'admin', 'ax', 'jquery', 'steps', 'laydate', 'func'], function () {
    var $ = layui.jquery;
    var $ax = layui.ax;
    var form = layui.form;
    var admin = layui.admin;
    var laydate = layui.laydate;

    //加载
    var resultData;
    var status = H_APPEAL;

    //选择
    var selectMaterials = [];
    var materielSelectList = [];

    var finalSelectMaterials = [];
    var selectWorker;
    var selectReviewWorker;

    //==渲染

    //step
    $("#step_demo").step();



    //获取详情信息，填充表单

    if (!Feng.isUndefined(Feng.getUrlParam("purchaseId"))) {
        var ajax = new $ax(Feng.ctxPath + "/api/purchase/detail?purchaseId=" + Feng.getUrlParam("purchaseId"));
        result = ajax.start();
        form.val('purchaseForm', result.data);
        resultData = result.data;

        // 反显
        status = resultData.status + '';
        selectWorker = resultData.worker;
        selectReviewWorker = resultData.reviewWorker;
        if (!Feng.isUndefined(resultData.materielList)) {
            var materielListData = JSON.parse(resultData.materielList);
            selectMaterials = materielListData;
        }

    }

    loadResultData();

    //加载信息
    function loadResultData() {

        // 进度
        loadStep();
        //UI控制
        loadUIControl();
        //物料
        loadMaterialList();
        // 人员
        loadWorkerList();
        loadReviewWorkerList();
    }

    //加载进度

    function loadStep() {
        if (!Feng.isUndefined(resultData)) {
            status = resultData.status + '';
        }
        // step
        $("#step0").removeClass("step-current");
        $("#step" + status).addClass("step-current");
    }

    function getStatusDesc(status) {
        if (status === H_APPEAL) {
            return H_APPEAL_DESC;
        } else if (status === H_INPUT) {
            return H_INPUT_DESC;
        } else if (status === H_ORDERED) {
            return H_ORDERED_DESC;
        } else if (status === H_DONE) {
            return H_DONE_DESC;
        } else {
            return "无";
        }
    }

    //UI控制
    function loadUIControl() {
        var status = H_APPEAL;
        if (!Feng.isUndefined(resultData)) {
            status = resultData.status + '';
        }
        var statusDesc = getStatusDesc(status);
        var statusButton = statusDesc.substring(0, statusDesc.length - 2);
        $("#comfirmSpan").html(statusButton);
        $("#statusTip").html(statusDesc);
        $("#timeForm").addClass("layui-not-events");


        //禁止点击
        if (status !== H_APPEAL) {

            //物料
            $("#materielForm").addClass("layui-not-events");
            $("#addMaterielForm").css("display", "none");
            //时间
            if (status === H_INPUT) {
            } else if (status === H_ORDERED) {
            } else {
                $("#comfireButton").addClass("layui-not-events");
            }
            //人员
            $("#workerForm").addClass("layui-not-events");

        }

    }

    //=========== 加载工作人员 ========== //

    function loadWorkerList() {

        $("#workerSelect").html('');
        var ajax = new $ax(Feng.ctxPath + "/mgr/allList", function (data) {
            for (var i = 0; i < data.data.length; i++) {
                var name = data.data[i].name;
                var account = data.data[i].account;
                var value = account + "-" + name;
                var select = '';
                if (value === selectWorker) {
                    select = 'selected';
                }
                if (i === 0 && Feng.isUndefined(selectWorker) && value!==selectWorker) {
                    selectWorker = value;
                    select = 'selected';
                }
                var selected = select;
                $("#workerSelect").append('<option value="' + value + '"  '+selected+'>' + value + '</option>');
            }
            form.render();

        }, function (data) {
        });
        ajax.start();
    }
    form.on('select(workerSelect)', function (data) {
        selectWorker = data.value;
    });

    function loadReviewWorkerList() {

        $("#reviewWorkerSelect").html('');
        var ajax = new $ax(Feng.ctxPath + "/mgr/allList", function (data) {
            for (var i = 0; i < data.data.length; i++) {
                var name = data.data[i].name;
                var account = data.data[i].account;
                var value = account + "-" + name;
                var select = '';

                if (value === selectReviewWorker) {
                    select = 'selected';
                }
                if (i === 0 && Feng.isUndefined(selectReviewWorker) && value!==selectReviewWorker) {
                    selectReviewWorker = value;
                    select = 'selected';
                }
                var selected = select;
                $("#reviewWorkerSelect").append('<option value="' + value + '"  '+selected+'>' + value + '</option>');
            }
            form.render();

        }, function (data) {
        });
        ajax.start();
    }
    form.on('select(reviewWorkerSelect)', function (data) {
        selectReviewWorker = data.value;
    });


    /**
     * 反显列表
     */
    function mutilMateriels() {

        if (Feng.isArray(selectMaterials)) {
            for (var i = 0; i < selectMaterials.length; i++) {
                var materiel = selectMaterials[i];
                loadSingleMaterielItemList(i,materiel.desc,materiel.number);
            }

        }

    }
    /**
     * 增加一个选项
     */
    function loadSingleMaterielItemList(index, desc ,number) {


        var i = index;
        var selectClassName = 'materiel_name_' + i;
        var numberClass = 'materiel_number_' + i;

        var nameForm = '<div class="layui-inline layui-col-md5"><label class="layui-form-label">物料</label>' +
            '<div class="layui-input-block">' +
            '<input id= ' + selectClassName + ' name=' + selectClassName + ' type="text" value='+desc+' class="layui-input"/>' +
            '</div>' +
            '</div>';

        var numberForm = '<div class="layui-inline layui-col-md5"><label class="layui-form-label">数量(只)</label>' +
            '<div class="layui-input-block">' +
            '<input id= ' + numberClass + ' name=' + numberClass + ' type="text" value='+number+' class="layui-input"/>' +
            '</div>' +
            '</div>';

        $("#materielItemList").append(nameForm);
        $("#materielItemList").append(numberForm);
        form.render();

    }


    /**
     * 加载物料
     */
    function loadMaterialList() {

        var ajax = new $ax(Feng.ctxPath + "/api/materiel/list", function (data) {
            for (var i = 0; i < data.data.length; i++) {
                var name = data.data[i].title;
                var value = data.data[i].materielId;
                var specs = data.data[i].specs;
                var unit = data.data[i].unit;
                var dict = {"value": value, "name": name, "specs": specs, "unit": unit};
                materielSelectList.push(dict);
            }
            mutilMateriels();
            form.render();
        });
        ajax.start();
    }


    /**
     * 增加一个选项
     */
    function addMaterielItemList(index, value ,number) {


        var i = selectMaterials.length;
        if (index !== null) {
            i = index;
        }
        if (number === null) {
            number = 0;
        }

        var selectClassName = 'materiel_name_' + i;
        var numberClass = 'materiel_number_' + i;

        var nameForm = '<div class="layui-inline layui-col-md4">' +
            '<label class="layui-form-label">物料</label>' +
            '<div class="layui-input-block" style="line-height: 38px">' +
            '<input id="materielName"  name="materielName"  type="hidden" class="layui-input"> ' +
            '<select name="materielName" id=' + selectClassName + ' lay-filter=' + selectClassName + '>' +
            '</select>' +
            '</input>' +
            '</div>' +
            '</div>';

        var numberForm = '<div class="layui-inline layui-col-md5"><label class="layui-form-label">数量(只)</label>' +
            '<div class="layui-input-block">' +
            '<input id= ' + numberClass + ' name=' + numberClass + ' type="text" value='+number+' class="layui-input"/>' +
            '</div>' +
            '</div>';

        $("#materielItemList").append(nameForm);
        $("#materielItemList").append(numberForm);

        //重新加载

        reloadMaterielItem(selectClassName, i, value);
        form.render();

    }

    /**
     * 增加后刷新select
     * @param selectClassName
     */
    function reloadMaterielItem(selectClassName, index, value) {

        var selectItem = $("#" + selectClassName);
        $(selectItem).html('');
        for (var i = 0; i < materielSelectList.length; i++) {
            var item = materielSelectList[i];
            var desc = item.name + ' 规格:' + item.specs + item.unit;

            var select = '';
            if (value!==null && item.value === value) {
                select = 'select';
                selectMaterials.push(item.value);
            }else if (i === 0) {
                select = 'select';
                selectMaterials.push(item.value);
            }

            var option = '<option value="' + item.value + '" ' + select + '">' + desc + '</option>';
            $(selectItem).append(option);


        }

        form.on('select(' + selectClassName + ')', function (data) {
            var materielId = data.value;
            selectMaterials[index] = materielId;
        });
    }

    function makeMaterialListRequest() {

        for (var i = 0; i < selectMaterials.length; i++) {
            var materiel = {};
            var materielId = selectMaterials[i] + '';
            var numberClass = "materiel_number_" + i;
            var number = $("#" + numberClass).val();
            if (!Feng.isUndefined(number)) {
                materiel.number = number;
            }
            materiel["value"] = materielId;
            for (var j=0;j<materielSelectList.length;j++){
                var item = materielSelectList[j];
                var value = item['value'] + '';
                if (materielId===value) {
                    var desc = item.name + ' 规格:' + item.specs + item.unit;
                    materiel["name"] = item.name;
                    materiel["desc"] = desc;
                }
            }
            finalSelectMaterials.push(materiel);
        }

    }

    function buildRequest() {


        status = H_APPEAL;
        if (!Feng.isUndefined(resultData)) {
            status = resultData.status + '';
        }

        //投放阶段
        if (status === H_APPEAL) {

            //构造请求体
            makeMaterialListRequest();


            if ($("#title").val() === '') {
                Feng.error("计划标题不能为空");
                return false;
            }
            if (Feng.isUndefined(selectWorker)) {
                Feng.error("执行人都不能为空");
                return false;
            }

            if (Feng.isUndefined(selectReviewWorker)) {
                Feng.error("审核人都不能为空");
                return false;
            }

            if (Feng.isArray(selectMaterials) === false) {
                Feng.error("原料不能为空");
                return false;
            }

        }


        return true;
    }


    //表单提交事件
    form.on('submit(btnSubmit)', function (data) {


        var result = buildRequest();
        if (result === false) {
            return;
        }

        data.field.worker = selectWorker;
        data.field.reviewWorker = selectReviewWorker;
        if (status === H_APPEAL) {
            data.field.materielList = JSON.stringify(finalSelectMaterials);
        }

        var url = "/api/purchase/addItem";
        var add = true;
        if ($.trim(data.field.purchaseId) !== '') {
            url = "/api/purchase/editItem";
            add = false;
        }

        var ajax = new $ax(Feng.ctxPath + url, function (data) {
            if (add === true) {
                Feng.success("新增成功！");
                window.location.href = Feng.ctxPath + '/api/purchase'
            } else {
                Feng.success("更新成功！");
                window.location.reload();
            }


        }, function (data) {
            Feng.error("请求失败！" + data.responseJSON.message)
        });
        ajax.set(data.field);
        ajax.start();

        return false;
    });


    // 添加按钮点击事件
    $('#btnExp').click(function () {
        addMaterielItemList(null, null,null);
    });

    //返回按钮
    $("#backupPage").click(function () {
        window.location.href = Feng.ctxPath + '/api/purchase'
    });

});